package com.zy.explore.file.interfaces.facade.v1;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zy.explore.common.interfaces.vo.ResultVO;
import com.zy.explore.file.application.service.OssService;
import com.zy.explore.file.infrastructure.constant.OssRouter;
import com.zy.explore.file.interfaces.feign.OssFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * description OSS示例Facade
 *
 * @author 🇨🇳中国印🇨🇳
 * @date 2022年01月27日 22:51:30
 */
@Api(tags = {"OSS文件上传服务"})
@RestController
@RequestMapping(OssRouter.OSS)
public class AliOssFacade implements OssFeign {

    @Resource
    private OssService ossService;

    /**
     * 上传MultipartFile返回下载地址
     *
     * @param file 上传的文件
     * @return 返回下载地址
     * @throws IOException IO异常
     */
    @Override
    @ApiOperationSupport(order = 10)
    @ApiOperation("上传文件至OSS返回下载地址")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "file", dataTypeClass = File.class, name = "file", value = "文件")
    })
    @PostMapping(value = OssRouter.UPLOAD, headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<String> upload(@RequestPart("file") MultipartFile file) throws IOException {
        String downloadUrl = ossService.uploadFile(file);
        return ResultVO.getSuccess(downloadUrl);
    }

    /**
     * 上传MultipartFile返回下载地址
     *
     * @param file 上传的文件
     * @return 返回下载地址
     * @throws IOException IO异常
     */
    @Override
    @ApiOperationSupport(order = 20)
    @ApiOperation("上传文件至OSS返回下载地址(流式上传)")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "file", dataTypeClass = File.class, name = "file", value = "文件")
    })
    @PostMapping(value = OssRouter.UPLOAD_BY_BYTES, headers = "content-type=multipart/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultVO<String> uploadByBytes(@RequestPart("file") MultipartFile file) throws IOException {
        String downloadUrl = ossService.uploadFile(file.getBytes(), file.getOriginalFilename(), file.getContentType(), file.getOriginalFilename());
        return ResultVO.getSuccess(downloadUrl);
    }

}
